package com.instpower.things.handlers;

import com.alibaba.fastjson.JSONObject;
import com.instpower.things.config.Configs;
import com.instpower.things.entity.CabinetCacheVO;
import com.instpower.things.service.MessageService;
import com.instpower.things.transport.DataBuffer;
import com.instpower.things.transport.Request;
import com.instpower.things.instpower.Connection;
import com.instpower.things.instpower.Handler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Handler08F5Action
 * @Author: hellmash@gmail.com
 * @Date: 2020/3/16
 * @Version: 1.0.0
 * @Description: 充电宝借还
 */
@Component(value = "CMD08F5")
public class Handler08F5Action extends Handler<Request> {

    @Autowired
    private MessageService messageService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public short getId() {
        return Configs.RENT;
    }

    @Override
    public void execute(Connection connection, Request request) throws UnsupportedEncodingException {
        String sn = request.getHeader().getAddr();

        logger.info("[{}]:Exec - CMD08F5 - BEGIN",sn);

        DataBuffer buffer = request.getData().encode();
        Integer orderId = buffer.readInt();
        byte rentType   = buffer.readByte();
        byte slotNum    = buffer.readByte();
        byte result     = buffer.readByte();
        //release after read
        buffer.release();

        //删除临时缓存
        String finishKey = String.format(Configs.RENT_08F6_FINISH, orderId);
        //超过08F6发送的轮询间隔时间
        redisTemplate.opsForValue().set(finishKey, "1", 20, TimeUnit.SECONDS);

        //不正常状态!=0时由于没有唤起09d9联机交易，需要回复队列消息
        if(result != 0){
            String cacheOrderNo = String.format(Configs.ANKER_RENT_RETURN_ORDER_NO, (sn + slotNum));
            String orderNoCache = redisTemplate.opsForValue().get(cacheOrderNo);
            boolean isReturn = (0x01 == rentType);
            messageService.send(sn,getBatterySn(sn,(int)slotNum),isReturn,slotNum,orderNoCache,rentType,result,"");
            logger.debug("交易号[{}]借还失败:{}", orderId, result);
        }
        logger.debug("[{}]:借还指令完成，进入联机处理",sn);
        logger.info("[{}]:Exec - CMD08F5 - BEGIN",sn);
    }


    /**
     * 获取机柜缓存
     * @param cabinetSn
     * @return
     */
    public CabinetCacheVO getCabinetCache(String cabinetSn) {
        String cabinetInfo = (String) redisTemplate.opsForValue().get(cabinetSn);
        logger.info("从redis取机柜数据,cabinetSn:{},值:{}",cabinetSn,cabinetInfo);
        if (null != cabinetInfo && !"".equals(cabinetInfo)) {
            return JSONObject.parseObject(cabinetInfo, CabinetCacheVO.class);
        }
        return null;
    }

    /**
     * 获取电池SN
     * @param cabinetSn
     * @param slotNum
     * @return
     */
    public String getBatterySn(String cabinetSn,Integer slotNum) {
        CabinetCacheVO cabinetCacheVO = this.getCabinetCache(cabinetSn);
        if (null == cabinetCacheVO) {
            logger.error("机柜[{}]心跳信息不存在", cabinetSn);
        }
        List<CabinetCacheVO.SlotInfoBean> slotInfos = cabinetCacheVO.getSlot_info();
        for (CabinetCacheVO.SlotInfoBean slot: slotInfos) {
            if (slotNum == slot.getSlot_num()){
                return slot.getBattery_sn();
            }
        }
        return null;
    }
}
